package javase.jmx.remote;


import java.io.IOException;
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class RemoteClient {

	public static void main(String[] args) throws Exception {
		testCommonOperations();
	}

	private static void testCommonOperations() throws Exception {
        echo("Create an RMI connector client and connect it to the RMI connector server");
        // service should be launched with parameters -Dcom.sun.management.jmxremote.port=9999 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
        JMXConnector jmxConnector = JMXConnectorFactory.connect(url, null);
        
        emtyLine();
        echo("Get an MBeanServerConnection");
        MBeanServerConnection messageBeanServerConnection = jmxConnector.getMBeanServerConnection();

        performCommonOperations(messageBeanServerConnection);

        jmxConnector.close();
	}

	private static void performCommonOperations(MBeanServerConnection messageBeanServerConnector) throws Exception {
		printDomains(messageBeanServerConnector);
		emtyLine();
        echo("MBeanServer default domain = " + messageBeanServerConnector.getDefaultDomain());
        emtyLine();
        echo("MBean count = " + messageBeanServerConnector.getMBeanCount());

        printMBeanNames(messageBeanServerConnector);
	}

	private static void printMBeanNames(MBeanServerConnection messageBeanServerConnector) throws Exception {
		emtyLine();
		echo("Query MBeanServer MBeans:");
        Set<ObjectName> names = new TreeSet<ObjectName>(messageBeanServerConnector.queryNames(null, null));
        for (ObjectName name : names) {
            echo("\tObjectName = " + name);
        }
	}

	private static void printDomains(MBeanServerConnection messageBeanServerConnection) throws IOException {
		emtyLine();
		echo("Domains:");
		String domains[] = messageBeanServerConnection.getDomains();
        Arrays.sort(domains);
        for (String domain : domains) {
            echo("\tDomain = " + domain);
        }
	}
	
	private static void emtyLine() {
		echo("");
	}

    private static void echo(String msg) {
        System.out.println(msg);
    }

}

